package com.ruoyi.api;

import cn.dev33.satoken.stp.StpUtil;
import com.ruoyi.biz.domain.FrontUser;
import com.ruoyi.biz.service.IFrontUserService;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.exception.base.BaseException;
import com.ruoyi.domain.PasswordRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

@RestController
@RequestMapping("/api/frontUser")
@Slf4j
public class ApiFrontUserController {
    @Resource
    private IFrontUserService frontUserService;


    @GetMapping("/info")
    public AjaxResult getInfo(){
        FrontUser frontUser = frontUserService.selectFrontUserById(StpUtil.getLoginIdAsLong());
        return AjaxResult.success(frontUser);
    }

    @PutMapping("/update")
    public AjaxResult updateInfo(@RequestBody FrontUser frontUser){
        frontUserService.updateFrontUser(frontUser);
        return AjaxResult.success();
    }

    @PutMapping("/updatePassword")
    public AjaxResult updatePassword(@RequestBody PasswordRequest passwordRequest){
        // 校验新密码和确认密码是否一致
        String oldPassword = passwordRequest.getOldPassword();
        String newPassword = passwordRequest.getNewPassword();
        String confirmPassword = passwordRequest.getConfirmPassword();
        if (!newPassword.equals(confirmPassword)){
            throw new BaseException("新密码和确认密码不一致");
        }
        FrontUser frontUser = frontUserService.selectFrontUserById(StpUtil.getLoginIdAsLong());
        if (!frontUser.getPassword().equals(oldPassword)){
            throw new BaseException("旧密码不正确");
        }
        // 修改密码
        frontUser.setPassword(newPassword);
        frontUserService.updateFrontUser(frontUser);
        return  AjaxResult.success();
    }

}
